package com.inspur.edp.bef.bemanager.service;

import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityErrorCodeEnum;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityException;
import com.inspur.edp.bef.bizentity.gspbusinessentity.entity.BeConfigCollectionInfo;
import com.inspur.edp.bef.bizentity.gspbusinessentity.entity.GspBeExtendInfo;
import com.inspur.edp.bef.engine.core.BefEngineInfoCache;
import com.inspur.edp.cef.entity.config.CefConfig;
import com.inspur.edp.bef.extendinfo.server.api.IGspBeExtendInfoRpcService;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.ProcessMode;
import com.inspur.edp.metadata.rtcustomization.spi.MetadataSavedToDBExtend;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BESavedToDBExtend implements MetadataSavedToDBExtend {

    private static final Logger logger = LoggerFactory.getLogger(BESavedToDBExtend.class);
    @Override
    public void execute(GspMetadata gspMetadata, ProcessMode processMode){

        logger.info("执行元数据扩展,ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName());
        if(!"GSPBusinessEntity".equals(gspMetadata.getHeader().getType())) {
            if(gspMetadata.getHeader().getType()==null||"".equals(gspMetadata.getHeader().getType())){
                logger.error("元数据Type为null，更新config信息失败！ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName());
            }
            return;
        }
        GspBusinessEntity be = (GspBusinessEntity)gspMetadata.getContent();
        if(gspMetadata.getContent() == null){
            logger.error("参数元数据content为null！！！ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName());
        }
        IGspBeExtendInfoRpcService beInfoService = SpringBeanUtils.getBean(IGspBeExtendInfoRpcService.class);
        GspBeExtendInfo existing = beInfoService.getBeExtendInfo(be.getID());
        if(existing!=null) {
            logger.info("更新configInfo前删除重复,ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName());
            beInfoService.deleteBeExtendInfo(be.getID());
        }
        BefEngineInfoCache.removeBefEngineInfo(gspMetadata.getHeader().getId());

        try {
            List<GspBeExtendInfo> infos = new ArrayList();
            GspBeExtendInfo info = buildBeExtendInfo(processMode,be);
            if (be.getGeneratedConfigID() != null) {
                infos.add(info);
                logger.info("开始更新BE元数据configInfo，ID:"+gspMetadata.getHeader().getId()+"....configid:"+info.getConfigId());
                beInfoService.saveGspBeExtendInfos(infos);
            }else {
                logger.error("ConfigId生成为null，更新config信息失败！！！！ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName()+"....code:"+be.getCode());
            }
        }catch (Exception e) {
            logger.error("部署BE元数据失败！！！！ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName()+"...异常信息："+e);
            throw BusinessEntityException.createException(BusinessEntityErrorCodeEnum.GSP_BEMODEL_BUSINESS_ENTITY_0018, e);
        }
    }

    private GspBeExtendInfo buildBeExtendInfo(ProcessMode processMode, GspBusinessEntity be) {
        GspBeExtendInfo info = new GspBeExtendInfo();
        BeConfigCollectionInfo beConfigCollectionInfo = getBefConfigCollectionInfo(be);
        beConfigCollectionInfo.setProjectType(processMode);
        info.setId(be.getID());
        info.setConfigId(be.getGeneratedConfigID());
        info.setLastChangedOn(new Date());
        info.setBeConfigCollectionInfo(beConfigCollectionInfo);
        return info;
    }

    private BeConfigCollectionInfo getBefConfigCollectionInfo(GspBusinessEntity be) {
        CefConfig cefConfig = new CefConfig();
        cefConfig.setID(be.getGeneratedConfigID());
        cefConfig.setBEID(be.getID());
        String nameSpace = be.getCoreAssemblyInfo().getDefaultNamespace();
        cefConfig.setDefaultNamespace(nameSpace.toLowerCase());
        BeConfigCollectionInfo beConfigCollectionInfo = new BeConfigCollectionInfo();
        beConfigCollectionInfo.setConfig(cefConfig);
        return beConfigCollectionInfo;
    }
}
